package com.abvnet.project.water.project.service;

import com.abvnet.common.utils.StringUtils;
import com.abvnet.framework.config.AbvnetConfig;
import com.abvnet.project.water.project.domain.ProjectSummary;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.util.ClassUtils;
import org.springframework.util.ResourceUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * 项目总结 服务层实现
 * 
 * @author wolf
 * @date 2019-12-10
 */
public class WordGeneratorUtils {
    //配置信息,代码本身写的还是很可读的,就不过多注解了
    private static Configuration configuration = null;
    static {
        configuration = new Configuration();
        configuration.setDefaultEncoding("utf-8");
        try {
            String url = AbvnetConfig.getTemplatePath();
            System.out.println(url);
            configuration.setDirectoryForTemplateLoading(new File(url));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private WordGeneratorUtils() {
        throw new AssertionError();
    }

    public static void exportMillCertificateWord(String template, HttpServletRequest request, HttpServletResponse response, ProjectSummary projectSummary) throws IOException {
        Template freemarkerTemplate = configuration.getTemplate(template);
        File file = null;
        InputStream fin = null;
        OutputStream out = null;
        try {
            Map<String, String> map = parseToMap(projectSummary);
            file = createDoc(map, freemarkerTemplate);
            fin = new FileInputStream(file);

            response.setCharacterEncoding("utf-8");
            response.setContentType("application/msword");
            String fileName = map.get("name");
            if (template.equalsIgnoreCase("dataTemplate.ftl"))
                fileName += "项目数据统计.doc";
            else if (template.equalsIgnoreCase("summaryTemplate.ftl"))
                fileName += "项目总结.doc";

            response.setHeader("Content-Disposition", "attachment;filename="
                    .concat(String.valueOf(URLEncoder.encode(fileName, "UTF-8"))));

            out = response.getOutputStream();
            byte[] buffer = new byte[512];  // 缓冲区
            int bytesToRead = -1;
            // 通过循环将读入的Word文件的内容输出到浏览器中
            while((bytesToRead = fin.read(buffer)) != -1) {
                out.write(buffer, 0, bytesToRead);
            }
        } finally {
            if(fin != null) fin.close();
            if(out != null) out.close();
            if(file != null) file.delete(); // 删除临时文件
        }
    }

    private static File createDoc(Map<?, ?> dataMap, Template template) {
        String name =  dataMap.get("name") + "项目总结.doc";
        File f = new File(name);
        Template t = template;
        try {
            // 这个地方不能使用FileWriter因为需要指定编码类型否则生成的Word文档会因为有无法识别的编码而无法打开
            Writer w = new OutputStreamWriter(new FileOutputStream(f), "utf-8");
            t.process(dataMap, w);
            w.close();
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new RuntimeException(ex);
        }
        return f;
    }

    public static Map<String, String> parseToMap(ProjectSummary projectSummary) {
        Map<String, String> datas = new HashMap(32);
        datas.put("name", projectSummary.getProjectName());
        if (StringUtils.isNotEmpty(projectSummary.getProvinceName()))
            datas.put("pname", projectSummary.getProvinceName() + projectSummary.getCityName() + projectSummary.getZoneName());
        if (StringUtils.isNotEmpty(projectSummary.getAddress()))
            datas.put("address", projectSummary.getAddress());
        if (StringUtils.isNotEmpty(projectSummary.getSewageType()))
            datas.put("type", projectSummary.getSewageType());
        if (StringUtils.isNotEmpty(projectSummary.getDesignIntake()))
            datas.put("design", projectSummary.getDesignIntake());
        if (StringUtils.isNotEmpty(projectSummary.getActualIntake()))
            datas.put("actual", projectSummary.getActualIntake());
        if (StringUtils.isNotEmpty(projectSummary.getProjectPrice()))
            datas.put("price1", projectSummary.getProjectPrice());
        if (StringUtils.isNotEmpty(projectSummary.getTechPrice()))
            datas.put("price2", projectSummary.getTechPrice());
        if (StringUtils.isNotEmpty(projectSummary.getSummary()))
            datas.put("summary", projectSummary.getSummary());
        else
            datas.put("summary", "");
        if (StringUtils.isNotEmpty(projectSummary.getCodImage()))
            datas.put("cod", projectSummary.getCodImage().split("base64,")[1]);
        if (StringUtils.isNotEmpty(projectSummary.getNh3nImage()))
            datas.put("nh3n", projectSummary.getNh3nImage().split("base64,")[1]);
        if (StringUtils.isNotEmpty(projectSummary.getTotalNImage()))
            datas.put("totaln", projectSummary.getTotalNImage().split("base64,")[1]);
        if (StringUtils.isNotEmpty(projectSummary.getTotalPImage()))
            datas.put("totalp", projectSummary.getTotalPImage().split("base64,")[1]);
        if (StringUtils.isNotEmpty(projectSummary.getPhImage()))
            datas.put("ph", projectSummary.getPhImage().split("base64,")[1]);
        if (StringUtils.isNotEmpty(projectSummary.getSv30Image()))
            datas.put("sv30", projectSummary.getSv30Image().split("base64,")[1]);
        if (StringUtils.isNotEmpty(projectSummary.getDoImage()))
            datas.put("do", projectSummary.getDoImage().split("base64,")[1]);
        if (StringUtils.isNotEmpty(projectSummary.getTImage()))
            datas.put("t", projectSummary.getTImage().split("base64,")[1]);
        if (StringUtils.isNotEmpty(projectSummary.getWaterImage()))
            datas.put("water", projectSummary.getWaterImage().split("base64,")[1]);
        if (StringUtils.isNotEmpty(projectSummary.getMicroImage()))
            datas.put("micro", projectSummary.getMicroImage().split("base64,")[1]);
        return datas;
    }
}